package com.atguigu.flink.chapter06_timer;

import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.TimerService;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;


/*
        只要时间超过定时器的时间，定时器就会被触发！ 在EventTime中见的比较多！
        ProcessingTime是匀速的！
 */
public class Demo2_EventTimer
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
            //把系统的时钟调慢3s
            .<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner((e, ts) -> e.getTs());

        env.setParallelism(1);
        env
            .socketTextStream("hadoop103", 8888)
            .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           }).assignTimestampsAndWatermarks(watermarkStrategy)
            .keyBy(WaterSensor::getId)
            /*
                         如果当前的WaterSensor的 vc > 30，就指定一个定时器，在5s后触发预警
                         如果当前的WaterSensor的 vc < 10,取消定时器
                */
            .process(new KeyedProcessFunction<String, WaterSensor, String>()
            {
                /*
                        定时器触发时的执行逻辑。
                        定时器，好比基于一个绝对时间的的闹钟，只会触发一次！

                        Collector<WaterSensor> out 和  processElement(Collector<WaterSensor> out) 是同一个对象
                 */
                @Override
                public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                    out.collect(ctx.getCurrentKey() + "水位高于30，白色预警!");
                }

                long time = 0;
                @Override
                public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                    TimerService timerService = ctx.timerService();


                    if (value.getVc() > 30){

                        //永远落后数据一个身位
                        time = value.getTs() + 5000;

                        //注册定时器
                        timerService.registerEventTimeTimer(time);

                        System.out.println(ctx.getCurrentKey() +"注册了定时器:" + time);

                    }else if (value.getVc() < 10){

                        //删除之前指定的定时器
                        timerService.deleteEventTimeTimer(time);

                        System.out.println(ctx.getCurrentKey() + "删除了定时器:" + time);
                    }

                    out.collect(value.toString());
                }
            }).print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
    }
}
